#!/bin/sh

wifi_setup_radio()
{
	local radio=$1
	uci get wireless.${radio} >/dev/null 2>&1 && {
		uci -q batch <<-EOT
			set wireless.${radio}.disabled='0'
			set wireless.${radio}.country='CN'
			set wireless.${radio}.txpower='auto'
			set wireless.${radio}.channel='auto'
		EOT

		#FIXME fixup for mtk
		#test -n "`cat /proc/cpuinfo | grep -i MediaTek`" && {
		#	[ "x`uci get wireless.${radio}.hwmode`" = "x11a" ] || {
		#		chn=`cat /proc/uptime | cut -d. -f1`
		#		chn=$((chn%13+1))
		#		uci set wireless.${radio}.channel=$chn
		#	}
		#}

#		[ "x`uci get wireless.${radio}.hwmode`" = "x11a" ] || {
#			uci set wireless.${radio}.noscan='1'
#		}

		obj=`uci add wireless wifi-iface`
		test -n "$obj" && {
			uci set wireless.$obj.device="${radio}"
			uci set wireless.$obj.network='lan'
			uci set wireless.$obj.mode='ap'
			uci set wireless.$obj.ssid="${SSID}"
			uci set wireless.$obj.encryption='psk2'
			uci set wireless.$obj.wpa_group_rekey='0'
			uci set wireless.$obj.wpa_pair_rekey='0'
			uci set wireless.$obj.wpa_master_rekey='0'
			uci set wireless.$obj.key="${SSID_PASSWD}"
		}
	}
}

version=`uci get base_config.@status[0].version 2>/dev/null`
test -n "$version" || version=0

. /etc/openwrt_release
test -n "${DISTRIB_ID}" || DISTRIB_ID=NATCAP
DISTRIB_ID=`echo -n $DISTRIB_ID | tr a-z A-Z`

MACADDR=`cat /etc/board.json | grep macaddr | tr a-f A-F | grep -o "[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]:[0-9A-F][0-9A-F]" | head -n1`
test -n "$MACADDR" || MACADDR=`cat /sys/class/net/eth0/address | tr a-z A-Z`
test -n "$MACADDR" || MACADDR=`cat /sys/class/net/eth1/address | tr a-z A-Z`
test -n "$MACADDR" || MACADDR=`head -c6 /dev/urandom | hexdump -e '/1 "%02X:"' | head -c17`
test -n "$MACADDR" || MACADDR=`head -c6 /dev/random | hexdump -e '/1 "%02X:"' | head -c17`

test $version -lt 1 && {
	uci set luci.main.lang='zh_cn'
	uci commit luci

	uci get system.@system[0] >/dev/null 2>&1 && {
		uci set system.@system[0].hostname="${DISTRIB_ID}"
		uci set system.@system[0].zonename='Asia/Shanghai'
		uci set system.@system[0].timezone='CST-8'
		uci set system.@system[0].ttylogin='1'
		uci commit system
	}

	uci set mwan3.wan.enabled='0'
	uci commit mwan3

	uci set dhcp.lan.force='1'
	uci commit dhcp

	[ x`uci get firewall.@zone[0].name 2>/dev/null` = xlan ] && {
		[ x`uci get firewall.@zone[0].mtu_fix 2>/dev/null` = x1 ] || uci set firewall.@zone[0].mtu_fix='1'
	}
	uci commit firewall

	[ x`uci get dropbear.@dropbear[0] 2>/dev/null` = xdropbear ] && {
		uci set dropbear.@dropbear[0].PasswordAuth='off'
		uci set dropbear.@dropbear[0].RootPasswordAuth='off'
		uci set dropbear.@dropbear[0].Port='22'
		uci delete dropbear.@dropbear[0].Interface
		uci commit dropbear
		#cp /usr/share/base-config-setting/etc/dropbear/authorized_keys /etc/dropbear/authorized_keys && chmod 600 /etc/dropbear/authorized_keys
		touch /etc/dropbear/authorized_keys && chmod 600 /etc/dropbear/authorized_keys
	}
	test -d /www/luci-static || {
		uci set dropbear.@dropbear[0].PasswordAuth='on'
		uci set dropbear.@dropbear[0].RootPasswordAuth='on'
		uci commit dropbear
	}

	cp /usr/share/base-config-setting/etc/shadow /etc/shadow && chmod 600 /etc/shadow

	SUBFIX=`echo -n $MACADDR | sed 's/://g' | tr a-z A-Z | tail -c4`
	SSID=${DISTRIB_ID}_${SUBFIX}
	SSID_PASSWD=88888888

	while uci delete wireless.@wifi-iface[0] >/dev/null 2>&1; do :; done
	for radio in radio0 radio1 radio2 radio3 wifi0 wifi1 wifi2 wifi3; do
		wifi_setup_radio ${radio}
	done
	uci commit wireless

	version=1
}

test $version -lt 2 && {
#	uci get network.wan >/dev/null 2>&1 || {
#		local ifname=`uci get network.lan.ifname 2>/dev/null || echo eth0`
#		uci -q batch <<-EOT
#			set network.wan=interface
#			set network.wan.ifname="$ifname"
#			set network.wan.proto='dhcp'
#			set network.wan.metric='31'
#			set network.wan6=interface
#			set network.wan6.proto='dhcpv6'
#			set network.wan6.ifname="$ifname"
#			set network.wan6.reqaddress='try'
#			set network.wan6.reqprefix='auto'
#			set network.lan.ifname='macvlan0'
#			add network device
#			set network.@device[-1].name='macvlan0'
#			set network.@device[-1].type='macvlan'
#			set network.@device[-1].ifname="$ifname"
#			commit network
#		EOT
#	}

	lsmod | grep -q rndis_host && {
		uci -q batch <<-EOT
			set network.usbwan=interface
			set network.usbwan.proto='dhcp'
			set network.usbwan.ifname='usb0'
			set network.usbwan.metric='800'
			commit network
		EOT

		[ x`uci get firewall.@zone[1].name 2>/dev/null` = xwan ] && {
			wans="$(uci get firewall.@zone[1].network 2>/dev/null) usbwan"
			wans=$(for w in $wans; do echo $w; done | sort | uniq)
			wans=`echo $wans`
			uci set firewall.@zone[1].network="$wans"
			uci commit firewall
		}
	}

	config_line=
	which fdisk && {
		local partdev
		local ROOTDEV=/dev/sda
		. /lib/upgrade/common.sh
		if export_bootdevice && export_partdevice partdev 0; then
			ROOTDEV=/dev/${partdev}
		fi
		test -b ${ROOTDEV} && {
			sector_size=`fdisk -l ${ROOTDEV} | grep "^Sector size" | awk '{print $4}'`
			sector_size=$((sector_size+0))
			test ${sector_size} -gt 0 || sector_size=512
			lastsec=0
			if fdisk -l ${ROOTDEV} 2>/dev/null | grep -q "type: gpt"; then
				lastsec=`fdisk -l ${ROOTDEV} | grep ^${ROOTDEV} | head -n4 | tail -n1 | awk '{print $3}'`
				lastsec=$((lastsec+34))
			else
				lastsec=`fdisk -l ${ROOTDEV} | grep ^${ROOTDEV} | head -n2 | tail -n1 | awk '{print $3}'`
				lastsec=$((lastsec+1))
			fi
			config_line=`dd if=${ROOTDEV} bs=${sector_size} skip=${lastsec} count=1 2>/dev/null | head -n1 | grep "open=\|network=\|initscript="`
		}
	}
	echo ${config_line} | grep -o network=.* | sed 's/=/ /;s/,/ /g' | while read _ _ip _mask _gw _dns _; do
		test -n "$_dns" || _dns="114.114.114.114 8.8.8.8"
		test -n "$_ip" && test -n "$_mask" && test -n "$_gw" && test -n "$_dns" && {
			uci -q batch <<-EOT
				set network.wan.proto='static'
				set network.wan.metric='31'
				set network.wan.ipaddr="$_ip"
				set network.wan.netmask="$_mask"
				set network.wan.gateway="$_gw"
				set network.wan.dns="$_dns"
				commit network
			EOT
		}
		break
	done
	openport=`echo ${config_line} | grep -o open=[0-9]* | cut -d= -f2`
	test -n "$openport" && {
		uci -q batch <<-EOT
			set firewall.open=rule
			set firewall.open.target='ACCEPT'
			set firewall.open.src='wan'
			set firewall.open.proto='tcp'
			set firewall.open.dest_port="$openport"
			set firewall.open.name='open'
			commit firewall
		EOT
	}
	echo ${config_line} | grep -o initscript=.* | sed 's/=/ /;s/,/ /g' | while read _ data _; do
		echo $data | base64 -d >/tmp/initscript.sh && sh /tmp/initscript.sh
		rm -f /tmp/initscript.sh
		break
	done

	version=2
}

# kB
memtotal=`grep MemTotal /proc/meminfo | awk '{print $2}'`
cachesize=2048
dnsforwardmax=2048
nf_conntrack_max=16384
if test $memtotal -ge 1048576; then
	# >= 1024M
	cachesize=10000
	dnsforwardmax=10000
	nf_conntrack_max=262144
elif test $memtotal -ge 524288; then
	# >= 512M
	cachesize=10000
	dnsforwardmax=10000
	nf_conntrack_max=131072
elif test $memtotal -ge 262144; then
	# >= 256M
	cachesize=8192
	dnsforwardmax=8192
	nf_conntrack_max=65536
elif test $memtotal -ge 131072; then
	# >= 128M
	cachesize=4096
	dnsforwardmax=4096
	nf_conntrack_max=65536
elif test $memtotal -ge 65536; then
	# >= 64M
	cachesize=2048
	dnsforwardmax=2048
	nf_conntrack_max=32768
else
	# < 64M
	cachesize=1024
	dnsforwardmax=1024
	nf_conntrack_max=16384
fi

test $version -lt 3 && {
	uci -q get dhcp.@dnsmasq[0] || uci add dhcp dnsmasq
	uci set dhcp.@dnsmasq[0].cachesize="$cachesize"
	uci set dhcp.@dnsmasq[0].dnsforwardmax="$dnsforwardmax"
	uci set dhcp.@dnsmasq[0].localservice='0'
	uci set dhcp.@dnsmasq[0].localise_queries='1'
	uci set dhcp.@dnsmasq[0].rebind_protection='0'
	uci set dhcp.@dnsmasq[0].rebind_localhost='1'
	uci commit dhcp
	version=3
}

test $version -lt 4 && {
	uci set ucitrack.@fstab[0].exec='/sbin/block mount'
	uci commit ucitrack
	version=4
}

test $version -lt 5 && {
	cat /etc/group | grep -q ^lede: || echo lede:x:1000: >>/etc/group
	cat /etc/shadow | grep -q ^lede: || echo "lede:*:0:0:99999:7:::" >>/etc/shadow
	cat /etc/passwd | grep -q ^lede: || echo lede:*:1000:1000:lede:/var:/bin/false >>/etc/passwd
	version=5
}

test $version -lt 6 && {
	uci set uhttpd.main.rfc1918_filter='0'
	uci commit uhttpd
	version=6
}

test $version -lt 7 && {
	[ "x`uci get samba.@samba[0] 2>/dev/null`" = "xsamba" ] && {
		local name=`uci get system.@system[0].hostname 2>/dev/null || echo ${DISTRIB_ID}`
		uci set samba.@samba[0].homes='0'
		uci set samba.@samba[0].name="${name}"
		uci set samba.@samba[0].description="${name}"
		uci -q batch <<-EOF >/dev/null
			add samba sambashare
			set samba.@sambashare[-1].browseable='yes'
			set samba.@sambashare[-1].name='ShareDisks'
			set samba.@sambashare[-1].path='/mnt/'
			set samba.@sambashare[-1].users='lede'
			set samba.@sambashare[-1].read_only='no'
			set samba.@sambashare[-1].guest_ok='no'
			set samba.@sambashare[-1].create_mask='0644'
			set samba.@sambashare[-1].dir_mask='0755'
			commit samba
		EOF
	}
	version=7
}

# disable https by default
test $version -lt 8 && {
	uci set uhttpd.main.redirect_https='0'
	uci delete uhttpd.main.listen_https
	uci commit uhttpd
	version=8
}

# usb auto mount
test $version -lt 9 && {
	uci set fstab.@global[0].anon_mount='1'
	uci commit fstab
	version=9
}

# enable upnpd
test $version -lt 10 && {
	uci set upnpd.config.enabled='1'
	uci commit upnpd
	version=10
}

# enable https by default again
test $version -lt 11 && {
	uci set uhttpd.main.listen_https='0.0.0.0:443'
	uci commit uhttpd
	version=11
}

uci set fstab.@global[0].anon_mount_bak="`uci get fstab.@global[0].anon_mount_bak 2>/dev/null || uci get fstab.@global[0].anon_mount 2>/dev/null`"
uci set fstab.@global[0].anon_mount='0'
uci commit fstab

# fix usb auto umount bug
cp /usr/share/base-config-setting/mount.hotplug /etc/hotplug.d/block/10-mount

#FIXME fixup for openvpn client
uci delete openvpn_recipes.client_tun.pkcs12 2>/dev/null && uci commit openvpn_recipes

# sysctl overwrite
SYSCTL_LOCAL=/etc/sysctl.d/50-local.conf
mkdir -p /etc/sysctl.d
echo -n >$SYSCTL_LOCAL

echo net.nf_conntrack_max=$nf_conntrack_max >>$SYSCTL_LOCAL
echo net.ipv4.ip_early_demux=0 >>$SYSCTL_LOCAL
echo net.bridge.bridge-nf-call-iptables=0 >>$SYSCTL_LOCAL
echo net.ipv4.fib_multipath_hash_policy=1 >>$SYSCTL_LOCAL

#echo net.core.default_qdisc=fq_codel >>$SYSCTL_LOCAL
#echo net.core.default_qdisc=fq >>$SYSCTL_LOCAL
#echo net.ipv4.tcp_congestion_control=htcp >>$SYSCTL_LOCAL
#echo net.ipv4.tcp_congestion_control=bbr >>$SYSCTL_LOCAL

echo net.ipv4.tcp_congestion_control=cubic >>$SYSCTL_LOCAL
echo net.netfilter.nf_conntrack_helper=1 >>$SYSCTL_LOCAL

#replace wget
test -x /usr/bin/wget && rm -f /bin/wget && ln -s /usr/bin/wget /bin/wget

#disable switch_ports_status by default
/etc/init.d/switch_ports_status disable

touch /etc/config/base_config
uci get base_config.@status[0] >/dev/null 2>&1 || uci add base_config status >/dev/null 2>&1
uci set base_config.@status[0].version=$version
uci commit base_config
exit 0
